<?php

namespace app\model;

use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;

class Room extends Model
{
    protected $table = 'rooms';
    
    protected $fillable = [
        'room_code',
        'name',
        'status',
        'max_players',
        'current_players',
        'created_by',
        'auto_settlement_at',
        'auto_settled',
        'settlement_reason',
        'settlement_notification_sent',
        'tea_meal_limit',
        'tea_meal_percentage',
        'tea_meal_mode',
        'tea_meal_fixed_amount',
        'created_at',
        'updated_at'
    ];

    protected $casts = [
        'max_players' => 'integer',
        'current_players' => 'integer',
        'created_by' => 'integer',
        'auto_settlement_at' => 'datetime',
        'auto_settled' => 'boolean',
        'settlement_notification_sent' => 'boolean',
        'tea_meal_limit' => 'integer',
        'tea_meal_percentage' => 'integer',
        'tea_meal_fixed_amount' => 'integer',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    /**
     * 生成房间代码
     */
    public static function generateRoomCode()
    {
        $redis = \app\service\RedisService::getInstance();
        
        do {
            $code = $redis->generateRoomCode();
        } while (static::where('room_code', $code)->exists());
        
        return $code;
    }

    /**
     * 创建房间
     */
    public static function createRoom($data)
    {
        $room = new static();
        $room->room_code = static::generateRoomCode();
        $room->name = $data['name'];
        $room->status = 'waiting';
        $room->max_players = $data['max_players'] ?? 4;
        $room->current_players = 1; // 创建者自动加入
        $room->created_by = $data['user_id'];
        
        // 设置自动结算时间（2小时后）
        $room->auto_settlement_at = Carbon::now()->addHours(2);
        $room->auto_settled = false;
        $room->settlement_notification_sent = false;
        
        $room->save();
        
        // 缓存房间代码到Redis
        $redis = \app\service\RedisService::getInstance();
        $redis->setRoomCode($room->room_code, $room->id);
        
        return $room;
    }

    /**
     * 获取房间用户关系
     */
    public function roomUsers()
    {
        return $this->hasMany(RoomUser::class, 'room_id');
    }

    /**
     * 获取房间创建者
     */
    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /**
     * 更新房间状态
     */
    public function updateStatus($status)
    {
        $this->status = $status;
        $this->save();
    }

    /**
     * 更新当前人数
     */
    public function updateCurrentPlayers()
    {
        $this->current_players = $this->roomUsers()->where('status', 'active')->count();
        $this->save();
    }
}
